#include "mystdio.h"

myFILE*  my_fopen(const char* path, const char* flag_user)
{
    int fd = -1;//文件标识符
    int iscreate = 0;
    int flag_sys = 0;
    //1.打开方式
    if (strcmp(flag_user, "w") == 0)
    {
        flag_sys = O_WRONLY | O_CREAT | O_TRUNC;
        iscreate = 1;
    }
    else if (strcmp(flag_user, "r") == 0)
    {
        flag_sys = O_RDONLY;
    }
    else if (strcmp(flag_user, "a") == 0)
    {
        flag_sys = O_WRONLY | O_CREAT | O_APPEND;
        iscreate = 1;
    }
    else  
    {}

    //2.是否已创建---打开文件
    if (iscreate == 1)
        fd = open(path, flag_sys, 0666);
    else // 0
        fd = open(path, flag_sys);
    if (fd < 0) return NULL;

    //3.为语言(标准库中)的文件对象开辟空间
    myFILE* fp = (myFILE*)malloc(sizeof(myFILE));
    if (fp == NULL) return NULL;

    //4.初始化/更新文件对象内容
    fp->fileno = fd;
    fp->flag_flush = FLUSH_LINE;//对于屏幕文件是行刷新
    fp->cap = LINE_SIZE;
    fp->pos = 0;
    
    return fp;
}

void my_fflush(myFILE* fp)
{
    write(fp->fileno, fp->cache, fp->pos);
    fp->pos = 0;//重置
}

ssize_t my_fwrite(myFILE* fp, const char* data, int len)
{
    memcpy(fp->cache, data, len);//最好判断是否扩容
    fp->pos += len;
    //行刷新
    if ((fp->flag_flush & FLUSH_LINE) && fp->cache[fp->pos-1] == '\n')
    {
        //printf("11111111111111111111111111111\n");
        my_fflush(fp);
    }
    return len;
}

void my_fclose(myFILE* fp)
{
    my_fflush(fp);
    close(fp->fileno);
    free(fp);
    fp = NULL;
}
